<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise.prototype.then()</title>
</head>
<body>
    <h1>Promise.prototype.then()</h1>

    <script>
        // 基本用法
        Promise.resolve('foo')
            .then(string => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        string += 'bar';
                        resolve(string);
                    }, 1000);
                });
            })
            .then(string => {
                setTimeout(() => {
                    string += 'baz';
                    console.log(string); // foobarbaz
                }, 1000);
            });

        // then方法返回的是新的Promise实例
        const p1 = new Promise(function (resolve, reject) {
            resolve('hello');
        });

        const p2 = p1.then(result => result);
        console.log(p1 === p2); // false

        // 链式调用中的错误处理
        const p3 = new Promise((resolve, reject) => {
            resolve(1);
        }).then(result => {
            console.log(result); // 1
            throw new Error('出错了');
        }).then(result => {
            console.log('不会执行');
        }, error => {
            console.log(error.message); // "出错了"
        });
    </script>
</body>
</html> 